package com.service;

import com.dao.BaseDao;
import com.dao.SyncDao;
import com.protos.Peer;
import com.websocket.Observer;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 同步服务
 * @author zyf
 */
@Deprecated
public class SyncService implements Observer{

    private String name;
    private String propsPath;
    private BaseDao base;
//    private SyncDao sync;
//    private Connection conn;
    private ExecutorService executor = Executors.newCachedThreadPool();
//    private ExecutorService executor = Executors.newFixedThreadPool(20);

    public SyncService(String name, String propsPath) {
        this.name = name;
        this.propsPath = propsPath;
        init(propsPath);
    }

    public SyncService() {

    }

    private void init(String propsPath) {
        base = new BaseDao(propsPath);
/*        BaseDao.setPropsPath(propsPath);
        BaseDao base = BaseDao.getInstance();*/
        //通过driverManager获取connection
//        conn = base.getConnection();
        //获取druid的connetion
//        conn = base.getConnectionFromDruid();
//        sync = new SyncDao(conn);
    }

    @Override
    public void notify(final Peer.Event message) {
        if (message.hasBlk()) {
            final Peer.Block blk = message.getBlk();
            executor.submit(new Runnable() {
                @Override
                public void run() {
                    try {
                        Connection conn = base.getConnectionFromDruid();
                        System.out.println(conn);
                        new SyncDao(conn).saveBlock(blk);
                    } catch (SQLException e) {
                        e.printStackTrace();
                    }
                }
            });
        }
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public void setPropsPath(String propsPath) {
        this.propsPath = propsPath;
    }

//    public Connection getConn() {
//        return conn;
//    }

    public ExecutorService getExecutor() {
        return executor;
    }
}
